/**
 * @FileName: ProductController.java
 * @Author
 * @Description:
 * @Date 2016年4月20日 下午3:34:40
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.admin.product;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.controller.admin.BaseAdminController;
import cn.hpclub.server.model.Brand;
import cn.hpclub.server.model.Organization;
import cn.hpclub.server.model.product.Product;
import cn.hpclub.server.model.product.ProductSku;
import cn.hpclub.server.service.BrandService;
import cn.hpclub.server.service.DzgDailyService;
import cn.hpclub.server.service.ds.DsLog;
import cn.hpclub.server.service.product.ProductService;
import cn.hpclub.server.service.product.ProductService.CheckBoxBean;
import cn.hpclub.server.service.product.ProductSkuService;
import cn.hpclub.server.service.product.SkuService;
import cn.hpclub.server.util.DateKit;
import cn.hpclub.server.util.ExcelRenderUtil;
import cn.hpclub.server.util.ImageUtil;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.ObjectUtil;
import cn.hpclub.server.util.QueryHelper;
import cn.hpclub.server.util.Utils;
import cn.hpclub.server.util.excel.ExportUtils;

public class ProductController extends BaseAdminController<Product>{
    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);
    private static final String ORG_ID = "org";

    /**
     * 
     * @Title: list
     * @Description:产品列表
     */
    public void list(){
        int defaultOrgId = initOrgTree();
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        // logger.debug("keyword1,orgid:" + searchInfo.get("org"));

        // 筛选条件，机构选择所有
        boolean isAll = "-1".equals(searchInfo.get(ORG_ID));

        // 没有选机构，或者机构选所有的时候。取一个默认的orgid进行机构筛选。默认orgid为账号对应的顶级orgid
        if((searchInfo.get(ORG_ID) == null) || (isAll)){
            searchInfo.put(ORG_ID, String.valueOf(defaultOrgId));
        }

        // logger.debug("keyword2,orgid:" + searchInfo.get("org"));

        QueryHelper helper = ProductService.service.getQueryHelper(searchInfo);
        logger.debug(helper.getSelect() + helper.getSqlExceptSelect());

        findByPageForSearch(helper.getSelect(), helper.getSqlExceptSelect());

        // 准备品牌的数据
        List<Brand> brands = BrandService.service.findAll();
        setAttr("brands", brands);

        // 手动选所有的时候，选项跳回所有
        if(isAll){
            searchInfo.put(ORG_ID, "-1");
        }
        setAttrs(searchInfo);
        render("/admin/product_list.tpl");
    }

    /**
     * 商品导出功能
     */
    public void export(){
        int defaultOrgId = initOrgTree();
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        // 筛选条件，机构选择所有
        boolean isAll = "-1".equals(searchInfo.get(ORG_ID));
        // 没有选机构，或者机构选所有的时候。取一个默认的orgid进行机构筛选。默认orgid为账号对应的顶级orgid
        if((searchInfo.get(ORG_ID) == null) || (isAll)){
            searchInfo.put(ORG_ID, String.valueOf(defaultOrgId));
        }
        
        String[] excelHeaders = new String[]{"名称","所属品牌","属性","机型代码","价格","所属机构","创建人","上架时间","下架时间","是否启用 "};
        ExportUtils exportUtils = new ExportUtils(excelHeaders);
        String[] keys = new String[]{"product_name","brand_name","prop","model_code","cur_price","org_name","creator_name","put_on_time","put_off_time","isEnabled"};
        List<Record> list =  ProductService.service.exportProducts(searchInfo);
        try {
            exportUtils.exportExcel(keys,list,"yyyy-MM-dd HH:mm:ss",1);//此处最后一个参数表示从第一行开始填入数据（表头为第0行）
        } catch (IOException e) {
            logger.info("导出商品列表错误！");
        }
        SXSSFWorkbook workbook = exportUtils.getSXSSFWorkbook();
        render(new ExcelRenderUtil(workbook, "商品管理列表"));
    }
    
    
    
    /**
     * 
     * @Title: imageDetail
     * @Description:获取图片的size
     */
    public void imageDetail(){
        String imgUrl = getPara("url", null);
        logger.debug("methed:imageDetail;parameter imgUrl=====" + imgUrl);
        if(StrKit.notBlank(imgUrl)){
            imgUrl = imgUrl.replace("/upload", "");
        }
        File file = new File(getSystemConfig().getUploadDir() + imgUrl);

        logger.debug("file path=====" + file.getPath());
        Map<String, Long> imgDetailMap = ImageUtil.getImageSize(file);
        logger.debug("imageDetail=======" + JSONObject.toJSONString(imgDetailMap));
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, SUCCESS);
        if(ObjectUtil.isNotEmpty(imgDetailMap)){
            jsonMap.put("imgWidth", ObjectUtil.isNotEmpty(imgDetailMap.get("imgWidth"))
                    ? imgDetailMap.get("imgWidth").toString() : "0");
            jsonMap.put("imgHeight", ObjectUtil.isNotEmpty(imgDetailMap.get("imgHeight"))
                    ? imgDetailMap.get("imgHeight").toString() : "0");
            jsonMap.put("imgSize", ObjectUtil.isNotEmpty(imgDetailMap.get("imgSize"))
                    ? imgDetailMap.get("imgSize").toString() : "0");
        }
        renderJson(jsonMap);
    }

    /**
     * @Title: initOrgTree
     * @Description:初始化机构树列表
     * @return int 返回默认查询机构ID
     */
    private int initOrgTree(){
        List<Entry<String, String>> orgList = InterfaceUtil.getOrgList();
        if(orgList.size() > 0){
            /* 机构树可用 */
            setAttr("orgs", orgList);
            return Integer.parseInt(orgList.get(0).getValue());
        } else{
            /* 无机构树,显示当前机构名称 */
            List<Entry<String, String>> list = new ArrayList<Entry<String, String>>();
            int orgId = InterfaceUtil.getOrgId();
            String orgName = Organization.dao.getOrgNameByOrgId(orgId);
            if(!StrKit.isBlank(orgName)){
                list.add(new SimpleEntry<String, String>(orgName, String.valueOf(orgId)));
            }
            setAttr("orgs", list);
            return orgId;
        }
    }

    public void add(){
        /* 获取城市列表 */
        List<CheckBoxBean> regionList = ProductService.service.getRegionList();
        setAttr("regionList", regionList);
        setDateParam();
        toInputPage();
    }

    public void edit(){
        String id = getPara("id", null);
        if(StrKit.notBlank(id)){
            Record product = ProductService.service.getProductById(Integer.parseInt(id));
            // 获取商品的SKU和SKU_OPTS
            List<Record> skuInfo = SkuService.service.getSkuInfo();
            setAttr("selCateSkuOpts", JsonKit.toJson(skuInfo));
            setAttr("product", product);
            List<CheckBoxBean> regionList = ProductService.service.getRegionListForEdit(id);
            setAttr("regionList", regionList);
        }
        toInputPage();
    }

    /**
     * @Title: toInputPage
     * @Description:TODO void
     */
    private void toInputPage(){
        // 获取商品可选品牌信息
        List<Brand> brands = BrandService.service.getAllEnabledBrands();
        setAttr("brands", brands);
        render("/admin/product_input.tpl");
    }

    private void setDateParam(){
        Record product = new Record();
        product.set("put_on_time", new Date()); // 默认显示今天
        setAttr("product", product);
    }

    @Before(Tx.class)
    public void save(){
        String productId = getPara("productId", null);
        boolean isEdit = false;
        String skuOptions = getPara("skuOptions", "");
        int arrt_type = 3;
        if(skuOptions.contains("contract") && !skuOptions.contains("bare")){
            arrt_type = 1;
        } else if(skuOptions.contains("bare") && !skuOptions.contains("contract")){
            arrt_type = 2;
        }

        // 获取系统当前时间
        String operatedTime = DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss");

        Product product = new Product();
        product.set(Product.NAME, getPara("name", null));
        product.set(Product.TITLE, getPara("name", null)); // 四川大掌柜没有TITLE
        product.set(Product.BRAND_ID, getPara("brand_id", null));
        product.set(Product.CATE_ID, getPara("cate_id", null));
        product.set(Product.ATTR_TYPE, arrt_type);
        // 四川大掌柜 thumb 与 banner 在上传商品是统一在一处
        String banner_image = getPara("banner_img", null);
        String thumb = "";
        if(null != banner_image && !"".equals(banner_image)){
            // 去掉最后一个字符","
            /*
             * String semicolon = banner_image.substring(banner_image.length() -
             * 1, banner_image.length()); if(null != semicolon &&
             * ",".equals(semicolon)){ banner_image = banner_image.substring(0,
             * banner_image.length() - 1); }
             */
            // thum 取banner第一张图
            String img[] = banner_image.split(",");
            thumb = img[0];
        }
        // product.set(Product.THUMBNAIL, getPara("thumbnail", null));
        product.set(Product.THUMBNAIL, thumb);
        product.set(Product.BANNER_IMG, banner_image);
        product.set(Product.SORT, getParaToInt("sort", 0));
        product.set(Product.PROFIT, getPara("profit", "0.00"));
        product.set(Product.DESP_SUMMARY, getPara("desp_summary", null));
        product.set(Product.DESP_AFTERSALE, getPara("desp_aftersale", null));
        product.set(Product.DESP_DETAIL, getPara("desp_detail", null));
        product.set(Product.PUT_ON_TIME, getPara("put_on_time", null));
        product.set(Product.PUT_OFF_TIME, getPara("put_off_time", null));
        product.set(Product.VISIT, getPara("visit", null));
        product.set(Product.DEPOT_ID, getPara("depot_id", null));
        product.set(Product.IS_VISIBLE, 1);
        // product.set(Product.STATUS, getParaToInt("status", 0));
        product.set(Product.OPERATED_TIME, operatedTime);
        product.set(Product.CREATE_TIME, operatedTime);

        // 获取操作员ID
        int operator = InterfaceUtil.getAdminId();
        // 获取操作员机构ID
        int org_id = InterfaceUtil.getOrgId();

        product.set(Product.OPERATED_BY, operator);

        if(StrKit.notBlank(productId)){
            isEdit = true;
            // 更新商品信息
            product.set(Product.ID, productId);
            ProductService.service.setStatus(product, true, getParaToInt("status", 0));
            product.update();
        } else{

            // 新增商品信息
            product.set(Product.ORG_ID, org_id);
            product.set(Product.CREATOR, operator);
            // 新增，默认为禁用。编辑，不修改禁用启用状态。
            product.set(Product.ENABLED, 0);
            ProductService.service.setStatus(product, false, getParaToInt("status", 0));

            if(product.save()){
                productId = String.valueOf(product.getInt(Product.ID));
            }
        }

        // 是否点击了编辑SKU按钮
        boolean isSkuModified = getParaToInt("is_sku_modified", 0) == 1 ? true : false;
        // 如果编辑过sku，则先删除原有sku信息，再保存新的sku
        if(isEdit && isSkuModified){
            ProductSkuService.service.deleteProductSku(productId);
        }
        // 保存地域信息
        if(!isEdit){
            saveRegionInfo(productId, org_id);
        }

        // 如何是新增或者编辑且修改了sku，则保存sku信息
        if(!isEdit || (isEdit && isSkuModified)){
            String product_sku_array = getPara("product_sku_array", "");
            logger.debug("product_sku_array = " + product_sku_array);
            JSONArray productSkuArray = JSONArray.parseArray(product_sku_array);
            ConcurrentHashMap<String, String> productSkuInfo = null;
            for(Object psObj : productSkuArray){
                // 解析商品SKU数据
                productSkuInfo = Utils.getMapDataFromJson(psObj.toString());

                ProductSku productSku = setProductSku(productSkuInfo, productId);
                productSku.set(ProductSku.PRODUCT_ID, productId);
                productSku.set(ProductSku.ENABLED, 1);
                productSku.set(ProductSku.OPERATED_BY, operator);
                productSku.set(Product.OPERATED_TIME, operatedTime);

                // 保存商品SKU信息
                productSku.save();
            }
        }
        redirect("/product/list");
    }

    /**
     * @Title: saveRegionInfo
     * @Description:TODO
     * @param productId
     * @param org_id
     *            void
     */

    private void saveRegionInfo(String productId, int org_id){
        logger.debug("saveRegionInfo.productId=" + productId + ",org_id=" + org_id);
        Record record = Db.findFirst("SELECT CityCode FROM organization WHERE id=?", org_id);
        logger.debug("saveRegionInfo.city=" + record);
        if(record != null){
            int regionId = record.getInt("CityCode");
            ProductService.service.saveRegionInfo(productId, regionId);
        }
    }

    private ProductSku setProductSku(ConcurrentHashMap<String, String> productSkuInfo, String productId){
        ProductSku productSku = new ProductSku();

        for(Entry<String, String> item : productSkuInfo.entrySet()){
            productSku.set(item.getKey(), item.getValue());
        }

        return productSku;
    }

    /**
     * 
     * @Title: changeStatus
     * @Description:改变品牌的状态，是否启用
     */
    @Before(Tx.class)
    public void changeStatus(){
        String id = getPara("id");
        String targetStatus = getPara("target_status");
        boolean success = ProductService.service.changeStatus(id, targetStatus);
        if(success){
            if(StrKit.notBlank(targetStatus) && targetStatus.equalsIgnoreCase("1")){
                ajaxJsonSuccessMessage("已上架");
            } else{
                ajaxJsonSuccessMessage("已下架");
            }
        } else{
            ajaxJsonErrorMessage("操作失败");
        }
    }

    public void enable(){
        enableProduct(1, "启用");
    }

    public void disable(){
        enableProduct(0, "禁用");
    }

    private void enableProduct(int enabled, String actionName){
        logger.debug("enabled=" + enabled);
        String[] ids = getParaValues("ids");

        StringBuffer sb = new StringBuffer();
        sb.append("UPDATE product SET enabled = " + enabled + ",operated_time='"
                + DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss") + "' WHERE id IN (");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            ajaxJsonErrorMessage(actionName + "失败");
            return;
        }
        boolean success = Db.update(sb.toString(), (Object[])ids) > 0;
        if(success){
            ajaxJsonSuccessMessage(actionName + "成功");
        } else{
            ajaxJsonErrorMessage(actionName + "失败");
        }
    }

}
